package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;

@WebServlet(name = "RandomThreadControllerServlet", urlPatterns = "/RandomThreadControllerServlet")
public class RandomThreadControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 4587044197678502396L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = null;

			if (request.getUserPrincipal() == null) {
				user = User.getAnonymousUser();
			} else {
				user = User.get(request.getUserPrincipal());
			}

			Thread thread = Thread.getRandomThread(user);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/ThreadSelectedControllerServlet?boardid=" + thread.getBoardId() + "&threadid=" + thread.getThreadId());
			dispatcher.forward(request, response);

		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}
}